package edu.fiu.cis.personalize.server.berkDB;

import java.io.File;
import java.util.concurrent.ConcurrentHashMap;

import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;

public class BerkeleyDBConfigure {
	private static ConcurrentHashMap<String, Database> dbMap = new ConcurrentHashMap<String, Database>();
	private static final boolean TRANSACTIONAL = true;
	private static String BASE_DIR_NAME = "bdb/";

	private static String baseDir;

	public static void init(boolean clear) {
		if (clear){
			clear();
		}
		
		baseDir = BASE_DIR_NAME;
		File file = new File(baseDir);
		if (!file.exists()) {
			file.mkdir();
		}
		for (Database dbase : dbMap.values()) {
			dbase.close();
		}
		dbMap.clear();
	}

	private static void createDatabase(String name) {
		EnvironmentConfig environmentConfig = new EnvironmentConfig();
		environmentConfig.setAllowCreate(true);
		environmentConfig.setTransactional(TRANSACTIONAL);
		// perform other environment configurations
		File file = new File(baseDir + name);
		if (!file.exists()) {
			file.mkdir();
		}
		Environment environment = new Environment(file, environmentConfig);
		DatabaseConfig databaseConfig = new DatabaseConfig();
		databaseConfig.setAllowCreate(true);
		databaseConfig.setTransactional(TRANSACTIONAL);
		// perform other database configurations
		Database database = environment
				.openDatabase(null, name, databaseConfig);
		dbMap.put(name, database);
	}

	private BerkeleyDBConfigure() {
	}

	public static Database getDatabase(String name) {
		if (!dbMap.containsKey(name)) {
			createDatabase(name);
		}
		return dbMap.get(name);
	}

	public static Environment getEnvironment(String name) {
		return getDatabase(name).getEnvironment();
	}

	public static void close() {
		for (Database db : dbMap.values()) {
			db.close();
		}
	}

	public static void closeAndClear() {
		close();
		clear();
	}

	private static String[] databases = { "keys", "users","documents","queries","groups" };

	public static void clear() {
		for (String dbName : databases) {
			String dbDir = baseDir + dbName;
			deleteDB(dbDir);
		}
	}

	public static boolean deleteDB(String dbDir) {
		File file = new File(dbDir);
		if (!file.exists()) {
			return false;
		}
		String[] files = file.list();
		for (String f : files) {
			File fd = new File(dbDir + "/" + f);
			fd.delete();
		}
		return true;
	}

}
